<!--
 * @Author: mindaier 844199821@qq.com
 * @Date: 2023-12-07 10:24:29
 * @LastEditors: mindaier 844199821@qq.com
 * @LastEditTime: 2023-12-21 14:45:42
 * @FilePath: /meet-panel/index.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./css/element-plus.css" />
    <link rel="stylesheet" href="./css/element-theme-chalk.css" />
    <link rel="stylesheet" href="./css/index.css" />
    <title>meeting-panel</title>
  </head>
  <body>
    <div id="app">
      <div class="meeting-panel-page">
        <div class="content-wrap">
          <div class="content-header">
            <div class="header-left">
              <el-radio-group
                v-model="state.dateType"
                label="label position"
                @change="changeDateType"
              >
                <el-radio-button label="daily">日</el-radio-button>
                <el-radio-button label="weekly">周</el-radio-button>
                <el-radio-button label="monthly">月</el-radio-button>
              </el-radio-group>
              <el-button
                type="default"
                class="date"
                :disabled="disabled"
                @click="toCurrentDate"
              >
                {{ state.dateType === "daily" ? "今天" : state.dateType ===
                "weekly" ? "本周" : "本月" }}
              </el-button>
            </div>
            <div class="date-select">
              <div>
                <el-date-picker
                  v-if="state.dateType === 'daily'"
                  v-model="state.dailyDate"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                ></el-date-picker>
              </div>
              <div class="week-picker">
                <el-date-picker
                  v-if="state.dateType === 'weekly'"
                  v-model="state.weekDate"
                  type="week"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  :first-day-of-week="1"
                  placeholder="选择周"
                  @change="handleWeekChange"
                />
              </div>
              <div>
                <el-date-picker
                  v-if="state.dateType === 'monthly'"
                  v-model="state.monthDate"
                  type="month"
                  value-format="YYYY-MM"
                  placeholder="选择月"
                  @change="handleMonthChange"
                />
              </div>
            </div>
          </div>
          <div class="main">
            <div class="timescale">
              <div class="empty-item"></div>
              <div class="timescale-items">
                <div
                  class="timescale-item"
                  v-for="(item, index) in columnConfig[state.dateType]"
                  :key="index"
                >
                  {{ item.label }}
                </div>
              </div>
            </div>
            <div class="meeting-room-collapse">
              <div class="curTimeLine" :style="getCurTimeLineLeft()" v-if="showCurTimeLine"></div>
              <el-collapse v-model="activeNames">
                <el-collapse-item title="会议室" :name="1">
                  <div class="meeting-rooms-wrap">
                    <div
                      class="meeting-room"
                      v-for="item1 in state.roomsInfo"
                      :key="item1.roomId"
                    >
                      <div class="meeting-room-name" ref="roomNameRef">
                        {{item1.roomName}}
                        <span class="room-desc">
                          可容纳{{ item1.seatCount }} 人
                          <el-tag class="room-desc-tag" type="warning" v-if="item1.status"
                            >{{getStatusStr(item1.status) }}</el-tag
                          >
                        </span>
                      </div>
                      <div class="meeting-room-state" id="meetingRoom">
                        <div class="cell-box">
                          <div
                            ref="cellRef"
                            class="meeting-room-state-item"
                            v-for="(subitem, subindex) in columnConfig[state.dateType]"
                            :key="subindex"
                          >
                            <div class="vertical-line" v-if="state.dateType === 'daily'"></div>
                          </div>
                        </div>
                        <el-tooltip
                          class="box-item"
                          effect="light"
                          placement="top"
                          :offset="10"
                          v-for="(item2,index2) in state.roomAppsInfo"
                          :key="item2.appId+'33'"
                        >
                          <template #content>
                            <div class="custom-tooltip">
                              <div class="date-range">
                                {{ formatDate(item2.appBeginDate) }} -
                                {{ formatDate(item2.appEndDate)}}
                              </div>
                              <div class="user-name">
                                申请人:
                                <span class="name-text">{{item2.perName}}</span>
                              </div>
                              <div class="use-to">
                                用途: {{item2.description}}
                              </div>
                            </div>
                          </template>
                          <div
                            class="gray-bg"
                            v-if="item1.roomId === item2.roomId"
                            :style="getGrayBgStyle(item2)"
                          ></div>
                        </el-tooltip>
                      </div>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>

  <script src="./js/vue3.global.js"></script>
  <script src="./js/dayjs.js"></script>
  <script src="./js/dayjs.loocal.js"></script>
  <script src="./js/element-plus.js"></script>
  <script src="./js/element-plus-icons-vue.js"></script>
  <script src="./js/element-local.js"></script>
  
  <script src="./js/axios.js"></script>
  <script src="./js/request.js"></script>
  <script src="./js/config.js"></script>
  <script src="./js/data.js"></script>

  <script>
    const {
      createApp,
      reactive,
      ref,
      toRef,
      toRaw,
      watch,
      computed,
      onMounted,
      nextTick,
      shallowReactive,
      getCurrentInstance
    } = Vue;

    // debugger
    const app = createApp({
      setup() {
        const cellRef = ref();
        const roomNameRef = ref();
        const tableConfig2 = ref([]);

        const state = reactive({
          dateType: "daily",
          dailyDate: dayjs().format("YYYY-MM-DD"),
          weekDate: dayjs().format("YYYY-MM-DD"),
          monthDate: dayjs().format("YYYY-MM"),
          weekDateRange: {
            start: "",
            end: "",
          },
          weekInpVis: true,
          disabledClick: false,
          roomsInfo: [],
          roomAppsInfo: [],
          meetingRoomInfo: [],
          cellWidth: 68,
          roomNameWidth: 198,
        });
        const activeNames = ref([1]);
        let {ctx:that, proxy} = getCurrentInstance()

        const columnConfig = shallowReactive({
          daily: tableConfig,
          weekly: tableConfig1,
          monthly: tableConfig2.value,
        })

        const showCurTimeLine = computed(() => {
          if(state.dateType === 'daily' && state.dailyDate === dayjs().format('YYYY-MM-DD')) {
            return true
          } else if (state.dateType === 'weekly' && state.weekDateRange.start <= dayjs().format('YYYY-MM-DD') && state.weekDateRange.end >= dayjs().format('YYYY-MM-DD')) {
            return true
          } else if (state.dateType === 'monthly' && state.monthDate === dayjs().format('YYYY-MM')) {
            return true
          } else {
            return false
          }
        })

        const changeDateType = (type) => {
          initEleWidths();
          switch (type) {
            case "daily":
              break;
            case "weekly":
              initWeekDate();
              break;
            case "monthly":
              initHeaderColumn(state.monthDate);
              break;
            default:
              break;
          }
          query();
        };

        const initWeekDate = (flag) => {
          let x;
          let date;
          if (flag) {
            date = dayjs();
            x = dayjs().day();
          } else {
            date = dayjs(state.weekDate);
            x = date.day();
          }
          state.weekDate = date.add(1 - x, "day").format("YYYY-MM-DD");
          state.weekDateRange = {
            start: state.weekDate,
            end: dayjs(state.weekDate).add(6, "day").format("YYYY-MM-DD"),
          };
        };

        const handleMonthChange = (val) => {
          const [year, month] = dayjs(val).format("YYYY-MM").split("-");
          tableConfig2.value = getHeaderColumns(year, month);
        };

        const initHeaderColumn = (val) => {
          const [year, month] = val.split("-");
          tableConfig2.value = getHeaderColumns(year, month);
          columnConfig.monthly = tableConfig2.value;
        };

        const handleWeekChange = (val) => {
          const x = dayjs(val).day();
          state.weekDate = dayjs(val)
            .add(1 - x, "day")
            .format("YYYY-MM-DD");
          const end = dayjs(val).add(6, "day").format("YYYY-MM-DD");
          state.weekDateRange = {
            start: state.weekDate,
            end,
          };
          query();
        };

        const toCurrentDate = () => {
          if (state.dateType === "daily") {
            state.dailyDate = dayjs().format("YYYY-MM-DD");
            state.disabledClick = true;
          } else if (state.dateType === "weekly") {
            initWeekDate(true);
            query();
            state.disabledClick = true;
          } else if (state.dateType === "monthly") {
            state.monthDate = dayjs().format("YYYY-MM");
            state.disabledClick = true;
          }
        };

        const getCurTimeLineLeft = () => {
          let left = 0;
          const type = state.dateType;
          if(type === 'daily') {
            left = (dayjs().hour()-6) * state.cellWidth + state.roomNameWidth + dayjs().minute() * (state.cellWidth / 60)
          } else if (type === 'weekly') {
            const day = dayjs().day()
            left = (day - 1) * state.cellWidth + state.roomNameWidth + dayjs().hour() * (state.cellWidth / 24)
          } else if (type === 'monthly') {
            const day = dayjs().date()
            left = (day - 1) * state.cellWidth + state.roomNameWidth + dayjs().hour() * (state.cellWidth / 24)
          }
          return {
            left: left + "px",
          }
        };

        const disabled = computed(() => {
          let disabled = false;
          if (state.dateType === "daily") {
            disabled = state.dailyDate === dayjs().format("YYYY-MM-DD");
          } else if (state.dateType === "weekly") {
          } else if (state.dateType === "monthly") {
            disabled = state.monthDate === dayjs().format("YYYY-MM");
          }
          return disabled;
        });

        const cellSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
          if (row.colspan) {
            return [1, 18];
          }
        };

        const getStatusStr = (status) => {
          switch (status) {
            case 0:
              return "待审批";
            case 1:
              return "审批通过";
            case 2:
              return "审批未通过";
            case 3:
              return "草稿";
            default:
              return "";
          }
        };

        const getQueryParamsTime = (time) => {
          let paramsTime = {
            startDatetime: "",
            endDatetime: "",
          };
          switch (state.dateType) {
            case "daily":
              paramsTime.startDatetime = state.dailyDate + " 00:00:00";
              paramsTime.endDatetime =
                dayjs(state.dailyDate).add(1, "day").format("YYYY-MM-DD") +
                " 00:00:00";
              break;
            case "weekly":
              const week = state.weekDateRange;
              paramsTime.startDatetime =
                state.weekDateRange.start + " 00:00:00";
              paramsTime.endDatetime =
                dayjs(state.weekDateRange.end)
                  .add(1, "day")
                  .format("YYYY-MM-DD") + " 00:00:00";
              break;
            case "monthly":
              paramsTime.startDatetime =
                state.monthDate + "-" + "1" + " 00:00:00";
              paramsTime.endDatetime =
                dayjs(state.monthDate).add(1, "month").format("YYYY-MM") +
                "-" +
                "1" +
                " 00:00:00";
              break;
            default:
              break;
          }
          console.log("paramsTime", paramsTime);
          return paramsTime;
        };

        const query = async () => {
          const paramsTime = { ...getQueryParamsTime() };
          const params = {
            startDatetime: paramsTime.startDatetime || "2023-12-17 08:00:00",
            endDatetime: paramsTime.endDatetime || "2023-12-18 18:00:00",
          };
          // console.log('params', params);
          const token = '0f043702-64e2-48ca-88c6-2edefb4ee066'
          // const res = await postApi(`/meeting/getxgMeetingRoom?token=${token}`, params)
          console.log("res1 =====", res1);
          state.roomsInfo = res1.roomsInfo;
          state.roomAppsInfo = res1.roomAppsInfo;
          // formatData(res1)
          // console.log("meetingRoomInfo =====", state.meetingRoomInfo);
        };

        const formatData = (res1) => {
          for(let i=0; i<res1.roomsInfo.length; i++) {
            res1.roomsInfo[i].roomAppsInfo = []
            for(let j=0; j<res1.roomAppsInfo.length; j++) {
              res1.roomAppsInfo[j].roomId === res1.roomsInfo[i].roomId
              res1.roomsInfo[i].roomAppsInfo.push(res1.roomAppsInfo[j])
            }
          }
        }

        const formatDate = (date) => {
          const temp = date.split(' ')[1].slice(0, 5)
          return temp
        }

        const getGrayBgStyle = (item) => {
          const start = getTimeDHM(item.appBeginDate);
          const end = getTimeDHM(item.appEndDate);
          const { left, width } = getGrayBgPosition(start, end);
          return {
            left: left + "px",
            width: width + "px",
          };
        };

        const getGrayBgPosition = (start, end) => {
          let left = 0;
          let endPosition = 0;
          let width = 0;
          const sd = start.d;
          let sh = start.h;
          let sm = start.m;
          const ed = end.d;
          let eh = end.h;
          let em = end.m;
          const obj = {
            daily: tableConfig,
            weekly: tableConfig1,
            monthly: tableConfig2.value,
          };
          if (state.dateType === "daily") {
            const col1h = obj[state.dateType][0].label.split(":")[0];
            const colLasth =
              obj[state.dateType][obj[state.dateType].length - 1].label.split(
                ":"
              )[0];
            if (sh < col1h) {
              sh = col1h;
              sm = 0;
            }
            if (eh > colLasth) {
              eh = colLasth;
              em = 59;
            }
            let shIdx = obj[state.dateType].findIndex(
              (item) => item.label.split(":")[0] === sh
            );
            let ehIdx = obj[state.dateType].findIndex(
              (item) => item.label.split(":")[0] === eh
            );
            if (sh < obj[state.dateType][0].label.split(":")[0]) {
              left = 0;
            } 
            
            left = shIdx * state.cellWidth + (sm * state.cellWidth) / 60;
            endPosition = ehIdx * state.cellWidth + (em * state.cellWidth) / 60;
            width = endPosition - left;
          } else if (state.dateType === "weekly") {
            left =
              (dayjs(sd).day()-1) * state.cellWidth + (sh * state.cellWidth) / 24;
            endPosition =
              (dayjs(ed).day()-1) * state.cellWidth + (eh * state.cellWidth) / 24;
            if (sd === ed && sh === eh && sm !== em) {
              width = "5px";
            } else {
              width = endPosition - left > 5 ? endPosition - left : 5;
            }
          } else if (state.dateType === "monthly") {
            const sday = sd.split("-")[2];
            const eday = ed.split("-")[2];
            left = (sday - 1) * state.cellWidth + (sh * state.cellWidth) / 24;
            endPosition = (sday - 1) * state.cellWidth + (eh * state.cellWidth) / 24;
            if (sday === eday && sh === eh && sm !== em) {
              width = "2px";
            } else {
              width = endPosition - left > 2 ? endPosition - left : 2;
            }
            // console.log("grayBgWidth.value", width);
          }
          return {
            left,
            width,
          };
        };

        const getTimeDHM = (time) => {
          const timeArr = time.split(" ");
          const d = timeArr[0];
          const hm = timeArr[1];
          const [h, m] = hm.split(":");
          return { d, h, m };
        };

        const getToken = () => {
          const params = {
            userName: "rest",
            password: "da7aeb69-6c96-492f-b5f6-9d6d647b4de9",
            loginName: "gaoheng"
          };
          postApi(`/token`, params).then((res) => {
          });
        }

        const handleResize = () => {
          initEleWidths();
        }

        const initEleWidths = () => {
          nextTick(() => {
            state.cellWidth = cellRef.value && cellRef.value[0].getBoundingClientRect().width;
            state.roomNameWidth = roomNameRef.value && roomNameRef.value[0].getBoundingClientRect().width +
            roomNameRef.value[0].getBoundingClientRect().x;
            // that.$forceUpdate()
          })
        }

        onMounted(() => {
          initEleWidths();
          query();
          // window.addEventListener('resize', throttle(handleResize, 500))
          // getToken();
        });

        watch(
          () => state.dailyDate,
          () => {
            query();
          }
        );
        watch(
          () => state.monthDate,
          () => {
            query();
          }
        );

        return {
          state,
          tableConfig,
          tableConfig1,
          tableConfig2,
          activeNames,
          cellRef,
          roomNameRef,
          disabled,
          columnConfig,
          showCurTimeLine,
          handleWeekChange,
          toCurrentDate,
          cellSpanMethod,
          getStatusStr,
          getGrayBgStyle,
          handleMonthChange,
          changeDateType,
          getCurTimeLineLeft,
          getToken,
          formatDate,
        };
      },
    });
    app.use(ElementPlus, { locale: zhCn }).mount("#app");
  </script>
</html>
